<template>
  <view class="page">
    <view :model="dataForm" ref="form" class="form">
      <view class="form-view">
        <view class="group">
          <view class="title-view"> 服务商信息 </view>
          <view class="form-item">
            <view class="label"> 服务商：</view>
            <view class="value">川润智能 </view>
          </view>
          <view class="form-item">
            <view class="label"> 地址：</view>
            <view class="value">四川省成都市郫都区现代工业港港北六路85号 </view>
          </view>
          <view class="form-item">
            <view class="label"> 服务项目：</view>
            <view class="value">设备升级改造 </view>
          </view>
          <view class="form-item">
            <view class="label"> 服务类型：</view>
            <view class="value">技术改造 </view>
          </view>
        </view>

        <view class="group">
          <view class="title-view"> 设备信息 </view>
          <view class="form-item">
            <view class="label"> 设备编号 </view>
          </view>

          <view class="form-item">
            <v-input
              class="v-input"
              type="picker"
              placeholder="请选择设备"
            ></v-input>
          </view>

          <view class="form-item">
            <v-input class="v-input" placeholder="设备类型"></v-input>
          </view>

          <view class="form-item">
            <v-input class="v-input" placeholder="设备型号"> </v-input>
          </view>
          <view class="title-view"> 服务地址 </view>
          <view class="form-item" @click="onClickAddress">
            <v-input
              class="v-input"
              placeholder="请选择服务地址"
              :disabled="true"
            >
              <image
                :src="imgBaseUrlV2 + 'dingwei.png'"
                mode="widthFix"
                slot="ft"
                class="address-icon"
              />
            </v-input>
          </view>
        </view>

        <view class="group">
          <view class="title-view"> 客户联系方式 </view>
          <view class="form-item">
            <view class="label"> 提报人 </view>
          </view>
          <view class="form-item">
            <v-input class="v-input" placeholder="提报人"></v-input>
          </view>
          <view class="form-item">
            <view class="label">联系电话 </view>
          </view>
          <view class="form-item">
            <v-input class="v-input" placeholder="联系电话"></v-input>
          </view>
          <view class="form-item">
            <view class="label">描述 </view>
          </view>
          <view class="form-item">
            <view class="textarea-box">
              <textarea class="textarea" placeholder="请输入描述"></textarea>
              <Upload
                :edit="true"
                :imgCount="4"
                :imgList="dataForm.files"
              ></Upload>
            </view>
          </view>

          <view class="submit-btn" @click="submit">提交服务订单</view>
        </view>
      </view>
    </view>

    <Message ref="message"></Message>
  </view>
</template>

<script>
import detailModule from "@/common/mixins/detail-module";
import {
  getEquipmentOptions,
  getEquipmentsList,
  getEquipmentInfo,
} from "@/common/api/equipment.js";
import {
  getServiceProviderOptions,
  getServiceProviderInfo,
  getServiceProviders,
} from "@/common/api/service-provider.js";
import { postServiceOrderRecord } from "@/common/api/service-order-record.js";
import { mapState } from "vuex";
import Upload from "@/components/public/upload/index";
import vInput from "@/components/public/input/input";
import { imgBaseUrl, imgBaseUrlV0, imgBaseUrlV2 } from "@/common/config";
export default {
  mixins: [detailModule],
  components: {
    Upload,
    vInput,
  },
  data() {
    return {
      baseUrl: "",
      imgBaseUrlV0,
      imgBaseUrlV2,
      isEquipment: false,
      defaultValue: {
        equipment: [0],
        service: [0],
        serviceProject: [0],
      },
      serviceProvider: {},
      equipmentInfo: {
        model_no: "",
        no: "",
      },
      serviceProviderOptions: [],
      serviceProviderSelectShow: false,
      serviceProviderLabel: "请选择服务商",
      orderOptions: [
        {
          label: "综合",
          value: 0,
        },
        {
          label: "按评分",
          value: 1,
        },
        {
          label: "服务量",
          value: 2,
        },
      ],
      order: 0,
      orderTitle: "排序",
      serviceProjectOptionGroups: [],
      serviceProjectOptions: [],
      serviceProjectSelectShow: false,
      currentServiceProjectLabel: "请选择项目",
      serviceTypeShow: "无",
      equipmentOptions: [],
      equipmentSelectShow: false,
      currentEquipmentLabel: "请选择设备",
      dataQuery: {},
      dataForm: {
        device_id: "",
        servicer_id: "",
        service_content_id: "",
        address: "",
        contact_name: "",
        contact_mobile: "",
        desc: "",
        files: [],
      },
      rules: {
        servicer_id: [
          {
            required: true,
            type: "number",
            message: "服务商不能为空",
            trigger: ["change", "blur"],
          },
        ],
        service_content_id: [
          {
            required: true,
            type: "number",
            message: "服务项目不能为空！",
            trigger: ["change"],
          },
        ],
        device_id: [
          {
            required: true,
            type: "number",
            message: "设备不能为空！",
            trigger: ["change"],
          },
        ],
        contact_name: [
          {
            required: true,
            type: "string",
            message: "提报人不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        mobile: [
          {
            required: true,
            type: "string",
            message: "联系电话不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        address: [
          {
            required: true,
            type: "string",
            message: "服务地址不能为空！",
            trigger: ["change", "blur"],
          },
        ],
      },

      mixinViewOptions: {
        getURL: "/serviceList/serviceListDetail",
        isPage: false,
        isShowLoading: true,
        reachBottom: false,
        createdIsNeed: false,
        pullDown: true,
      },
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    // this.$refs.form.setRules(this.rules);
  },
  async onLoad(e) {
    if (e.id) {
      this.dataForm.id = e.id;
      this.getDataInfo();
    }
    if (e.servicer_id) {
      this.dataQuery.servicer_id = this.dataForm.servicer_id = e.servicer_id;
    }
    if (e.serviceProjectId) {
      this.service_content_id =
        this.dataForm.service_content_id =
        this.dataQuery.serviceProjectId =
          e.serviceProjectId;
    }
    if (e.device_id || e.equipmentId) {
      this.dataQuery.equipmentId = this.dataForm.device_id =
        e.device_id || e.equipmentId;
    }
    this.isEquipment = e.isEquipment;
    this.init();
    await this.initData();

    let tmpLabel = this.currentEquipmentLabel;
    uni.setNavigationBarTitle({
      title:
        "服务申请" +
        (tmpLabel && tmpLabel !== "请选择设备" ? "-" + tmpLabel : ""),
    });
  },
  computed: {
    ...mapState("User", ["userInfo"]),
    serviceProjectTextDisabled() {
      return this.serviceProjectOptions.length === 0 ? "text-disabled" : "";
    },
    serviceProjectIconDisabled() {
      return this.serviceProjectOptions.length === 0 ? "icon-disabled" : "";
    },
  },
  methods: {
    init() {
      let platform = uni.getSystemInfoSync().platform;
      if (platform == "android") {
        this.dataForm.source = "安卓";
      } else if (platform == "ios") {
        this.dataForm.source = "IOS";
      }
      // #ifdef MP
      this.dataForm.source = "小程序";
      // #endif
      this.dataForm.contact_name = this.userInfo.name;
      this.dataForm.contact_mobile = this.userInfo.mobile;
    },
    async initData() {
      uni.showLoading({
        title: "加载中",
        mask: false,
      });

      await Promise.all([
        this.getEquipmentsList(),
        this.getServiceProviders(),
        this.getServiceProviderOptions(),
      ])
        .then((res) => {})
        .catch((err) => {});

      uni.hideLoading();
    },
    getEquipmentsList() {
      if (this.userInfo.id) {
        console.log(this.dataForm.device_id, "?this.dataForm.device_id");
        if (this.dataForm.device_id) {
          getEquipmentInfo({
            id: this.dataForm.device_id,
          })
            .then((res) => {
              if (res.code !== this.$ERR_OK) {
                return;
              }
              let data = res.data || {};
              if (data) {
                this.equipmentInfo = data;
                this.currentEquipmentLabel = data.device_name;
              }
              this.equipmentOptions = [data];
            })
            .catch((err) => {});
        } else {
          return getEquipmentsList({
            id: this.dataForm.device_id,
          }).then((res) => {
            let data = res.data || [];
            let { list = [] } = data;
            list.forEach((i) => {
              i.label = i.device_name;
              i.value = i.id;
            });
            let item = list.find((i) => i.id == this.dataForm.device_id);
            console.log(item, "??item", list);
            if (item) {
              this.equipmentInfo = item;
              this.currentEquipmentLabel = item.label;
            }
            this.equipmentOptions = list;
          });
        }
      }
    },
    getServiceProviders() {
      if (this.userInfo.id) {
        console.log(this.service_content_id, "??this.service_content_id");
        if (this.service_content_id) {
          return getServiceProviderInfo({
            id: this.dataQuery.servicer_id,
          })
            .then((res) => {
              if (res.code !== this.$ERR_OK) {
                return;
              }
              let data = res.data;
              data = {
                ...data,
                label: data.name,
                value: data.id,
              };
              if (data) {
                this.serviceProviderLabel = data.name;
                this.getServiceProviderOptions(data.id);
              }
              console.log(data, "??data");
              this.serviceProvider = data;
              this.serviceProviderOptions = [data];
            })
            .catch((err) => {});
        }
        return getServiceProviders({
          sort: this.serviceSort || 0,
        }).then((res) => {
          let data = res.data || {};
          let { list = [] } = data;
          let tmp;
          list = list.map((i) => {
            if (
              this.dataForm.servicer_id &&
              i.id == this.dataForm.servicer_id
            ) {
              tmp = i;
            }
            return {
              ...i,
              label: i.name,
              value: i.id,
              address: i.address,
            };
          });
          console.log(tmp, "?tmp");
          if (tmp) {
            this.serviceProviderLabel = tmp.name;
            // this.getServiceProviderOptions(tmp.id);
          }
          this.serviceProviderOptions = list;
        });
      }
    },
    getServiceProviderOptions(id) {
      if (!id) return;
      return getServiceProviderOptions({
        id: id || "",
      })
        .then((res) => {
          let data = res.data || [];
          let tmp;
          data.forEach((i) => {
            if (
              this.dataQuery.serviceProjectId &&
              i.id == this.dataQuery.serviceProjectId
            ) {
              tmp = i;
            }
            i.label = i.title;
            i.value = i.id;
          });
          if (tmp) {
            this.currentServiceProjectLabel = tmp.title;
            this.serviceTypeShow = tmp.service_type;
          }
          this.serviceProjectOptions = data;
          uni.hideLoading();
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },

    onClickAddress() {
      uni.chooseLocation({
        success: function (res) {
          console.log("位置名称：" + res.name);
          console.log("详细地址：" + res.address);
          console.log("纬度：" + res.latitude);
          console.log("经度：" + res.longitude);
        },
      });
    },
    serviceProviderSelectConfirm(e) {
      this.currentServiceProjectLabel = "";
      let item = e[0];
      this.serviceProviderLabel = item.label;
      this.dataForm.servicer_id = item.value;
      let index = this.serviceProviderOptions.findIndex(
        (i) => i.id == item.value
      );
      let service = this.serviceProviderOptions[index];
      this.defaultValue.service = [index];
      this.serviceProvider.address = service.address;
      // serviceProviderOptions;
      uni.showLoading({
        title: "加载中",
      });
      this.getServiceProviderOptions(item.value);
    },
    changeOrder(e) {
      let item = this.orderOptions.find((item) => item.value == e);
      this.orderTitle = item.label;
      this.serviceSort = item.value;
      return this.getServiceProviders(item.value);
    },
    serviceProjectSelectConfirm(e) {
      let item = e[0];
      let index = this.serviceProjectOptions.findIndex(
        (i) => i.value == item.value
      );
      let type = this.serviceProjectOptions[index];
      this.defaultValue.serviceProject = [index];
      console.log(
        this.defaultValue.serviceProject,
        "?     this.defaultValue.serviceProject"
      );
      this.currentServiceProjectLabel = item.label;
      this.dataForm.service_content_id = item.value;
      this.serviceTypeShow = type.service_type;
    },
    equipmentSelectConfirm(e) {
      let item = e[0];
      let tmpL = (this.currentEquipmentLabel = item.label);
      let index = this.equipmentOptions.findIndex(
        (i) => i.value === item.value
      );
      this.defaultValue.equipment = [index];

      let equipmentOption = (this.equipmentInfo = this.equipmentOptions[index]);
      // let { type, model, address } = equipmentOption;
      // this.dataForm.address = address || null;
      this.dataForm.device_id = item.value;
      uni.setNavigationBarTitle({
        title: "服务申请" + (tmpL && tmpL !== "请选择设备" ? "-" + tmpL : ""),
      });
    },
    onUpload(item) {
      this.dataForm.img.push(item.url);
    },
    onDelete(index) {
      this.dataForm.img.splice(index, 1);
    },
    submit() {
      // this.$refs.form.validate(async (valid) => {
      // if (valid) {
      uni.showLoading({
        title: "提交中",
        mask: false,
      });
      postServiceOrderRecord(this.dataForm)
        .then((res) => {
          uni.hideLoading();
          if (res.code !== this.$ERR_OK) {
            return this.message.error(res.message || "提交订单失败");
          }
          return this.showModal({
            title: "提示",
            content: "提交订单成功,点击返回上一页",
            showCancel: false,
            success: (r) => this.$Router.go(-1),
          });
        })
        .catch(() => {
          uni.hideLoading();
        });
      // }
      // });
    },
    onOpenLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.dataForm.address = res.address;
          console.log("位置名称：" + res.name);
          console.log("详细地址：" + res.address);
          console.log("纬度：" + res.latitude);
          console.log("经度：" + res.longitude);
          this.message.success("获取地址成功");
        },
        fail: (err) => {
          console.log(err, "??err");
          this.message.error(err.errMsg || "获取地址失败");
        },
      });
    },
  },
  watch: {},
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/mixins';
@import '~@/common/stylus/variable';

.page {
  min-height: calc(100vh - var(--window-top));
  background-color: #4061bd;
}

.form {
  padding-top: 0;
  position: relative;
  padding: 30rpx;
  border-radius: 10rpx;

  .form-view {
    background: #ffffff;
    border-radius: 10rpx;
  }

  .title-view {
    font-size: 36rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: bold;
    color: color-active;
    padding: 16rpx 0;
  }

  .group {
    border-bottom: 1rpx solid #D8D8D8;
    padding: 20rpx;

    &:last-child {
      border-bottom: none;
    }
  }

  .form-item {
    display: flex;
    font-size: 32rpx;
    color: color-default;
    line-height: 50rpx;
    padding: 10rpx 0;
    font-family: PingFangSC-Regular, PingFang SC;

    >.label {
      flex: 0 0 160rpx;
      border: none;
      font-size: 32rpx;
      color: color-default;
      padding: 0;
      line-height: inherit;
      margin-right: 16rpx;
    }

    >.value {
      flex: 1;
    }
  }

  .submit-btn {
    margin-top: 30rpx;
    text-align: center;
    background-color: color-active;
    color: #fff;
    line-height: 90rpx;
    font-weight: 700;
    font-size: 36rpx;
    border-radius: 10rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: bold;
  }

  .address-icon {
    display: block;
    width: 40rpx;
    height: 40rpx;
    margin: 0 10rpx;
  }

  .textarea-box {
    background: #F6F6F6;
    border-radius: 10rpx;
    padding: 20rpx;
  }
}
</style>